<template>
  <div class="semi-hidden-input">
    <el-input :readonly="readonly" :value="displayValue" @input="onInput" autocomplete="off">
		<template #append>
			<el-button style="border: 0px;" :icon="currentIcon" @click="toggleVisibility"></el-button>
		</template>
    </el-input>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { View, Hide } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: String,
  maskLength: {
    type: Number,
    default: 3, // 默认遮盖长度为3
  },
  readonly: {
    type: Boolean,
    default: true, // 默认情况下不是 readonly
  },
});

const emit = defineEmits(['update:modelValue']);

const isHidden = ref(true);

// 计算显示的内容
const displayValue = computed(() => {
  const visiblePart = props.modelValue.slice(0, props.maskLength);
  const hiddenPartLength = Math.max(props.modelValue.length - props.maskLength, 0);
  const hiddenPart = '*'.repeat(hiddenPartLength);
  return isHidden.value ? visiblePart + hiddenPart : props.modelValue;
});


// 动态切换图标
const currentIcon = computed(() => {
  return isHidden.value ? View : Hide;
});

function onInput(value) {
  emit('update:modelValue', value);
}

function toggleVisibility() {
  isHidden.value = !isHidden.value;
}
</script>

<style scoped>
.semi-hidden-input {
  position: relative;
  display: inline-block;
  width: 100%;
}

</style>